/*
 * Copyright (c) 2009, Jeremy Sandell
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the author nor the names of its contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <hl7/common.hpp>
#include <hl7/message.hpp>
#include <hl7/except.hpp>
#include <hl7/util.hpp>

namespace hl7 {
    /**
     * message
     */
    message::message(const std::string &data,
                     const std::string &rsep,
                     const std::string &fsep,
                     const std::string &ssep) : hl7object(data,rsep,fsep,ssep),
                                                msg(data)
    {
    }


    /* TODO: We should be able to ascertain the name from the
     * fields..
     */

    void message::push(const std::string &name, std::vector<std::string> &fields)
    {
        msg_iter keyvalue = Message.find(name);

        /* If it doesn't exist already, convert to 
         * hl7segment and add it.
         */

        if(keyvalue == Message.end())
        {
            hl7segment seg(name, recordsep, fieldsep, subfieldsep);
            seg.push(fields);
            Message.insert(make_pair(name, seg));
        }
        else  
            /* Already have a segment of this type, append to our list.*/
            keyvalue->second.push(fields);

    }

    void message::push(const std::string &name, hl7segment &seg)
    {
        msg_iter keyvalue = Message.find(name);
        /* Add new if it doesn't exist already. */

        if(keyvalue == Message.end())
            Message.insert(make_pair(name, seg));
        else 
            /* Already have a segment of this type, append to our list.*/
            keyvalue->second.push(seg);
    }

    void message::parse(void)
    {
        using namespace pcrepp;
        Pcre re("^([A-Z0-9]{3})(.)(.)(.)(.)(.)(.)");

        std::vector<std::string> lines;
        std::vector<std::string> fields;
        std::string name;

        if(re.search(msg) == true)
        {
            /* If it doesnt have seven chars, assume it's
             * invalid;i.e., transmission error, corrupt file, 
             * etc.
             */

            if(re.matches() == 7)
            {
                /* Make sure the field separator matches
                 * the rest of the delimiters. 
                 */

                if(re.get_match(6) != re.get_match(1))
                    throw Exception("Field separator doesn't match delimiters.");

                if(fieldsep.empty())
                    fieldsep = re.get_match(1);

                if(subfieldsep.empty())
                    subfieldsep = re.get_match(2);

                /* Split into lines using record separator. */
                lines = util::split(msg, recordsep, lines);

                for(std::vector<std::string>::iterator line = lines.begin();
                    line != lines.end(); line++)
                {
                    name = (*line).substr(0, 3);
                    if(name.length() != 3)
                        continue;

                    fields = util::split((*line), fieldsep, fields);
                    this->push(name, fields);
                    fields.clear();
                }
            }
            else
                throw Exception("Corrupted MSH segment. (second pass)");
        }
        else
            throw Exception("Corrupted MSH segment.(first pass)");
    }

    bool message::contains(const std::string &name)
    {
        return (Message.find(name) != Message.end());
    }

    std::vector<std::string> & message::segments(std::vector<std::string> &f)
    {
        f.clear();

        for(msg_iter iter = Message.begin(); iter != Message.end(); iter++)
            f.push_back(iter->first);

        return f;
    }

    hl7segment & message::operator[](const std::string &name)
    {
        msg_iter iter = Message.find(name);

        if (iter != Message.end())
            return iter->second;
        else
            throw Exception("No such field.");
    }

    bool message::rm_sof(const std::string &n)
    {
        std::string::size_type srch = msg.find(n);

        if(srch != std::string::npos)
        {
            msg.erase(srch, 1);
            return true;
        }
        return false;
    }

    bool message::rm_eof(const std::string &n)
    {
        std::string::size_type srch = msg.find(n);

        if(srch != std::string::npos)
        {
            msg.erase(srch, 1);
            return true;
        }
        return false;
    }
};
